package com.ja.controller;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ja.config.WebsiteStateConfig;
import com.ja.domain.BankCard;
import com.ja.domain.Liushui;
import com.ja.domain.Lsltjl;
import com.ja.domain.LuckyCount;
import com.ja.domain.LuckyLotter;
import com.ja.domain.LuckyRecord;
import com.ja.domain.PagingData;
import com.ja.domain.TodayRecord;
import com.ja.domain.User;
import com.ja.domain.WhiteList;
import com.ja.sevice.AgencyCenterSevice;
import com.ja.sevice.IBankService;
import com.ja.sevice.ISystemConfigService;
import com.ja.sevice.IUserService;
import com.ja.sevice.LiushuiService;
import com.ja.sevice.LuckyRecordService;
import com.ja.sevice.YunyingbbService;
import com.ja.util.CodeUtil;
import com.ja.util.DateUtil;
import com.ja.util.IpAddrUtil;
import com.ja.util.JsonResult;
import com.ja.util.SessionListenerUtil;
import com.ja.util.UserNameUtil;
import com.ja.util.WebSocketJson;

/**
 * 项目名称：cp   
 * 类名称：UserController   
 * 类描述：   用户的注册管理类
 * 创建人：GL   
 * 创建时间：2018年10月10日 上午11:27:43   
 * @version
 */
@Controller
@RequestMapping("/u")
public class UserController {  

	@Autowired
	private IUserService userService;
	
	@Autowired
	private LiushuiService liushuiService;

	@Autowired
	private IBankService bankService;

	@Autowired
	private ISystemConfigService systemConfigService;

	@Autowired
	private LuckyRecordService luckyRecordService;
	
	@Autowired
	private YunyingbbService yunyingbbService;
	
	@Autowired
	private AgencyCenterSevice agencyCenterSevice;
	
	@RequestMapping("/userInfo")
	public void userInfo() {
	}

	@RequestMapping("/daili")
	public void daili() {
	}

	@RequestMapping("/editUserSelfData")
	public void editUserSelfData() {
	}
	
	@RequestMapping("/safe")
	public void safe() {
	}

	@RequestMapping("/set")
	public void set() {
	}

	/**
	 * 
	 *----TODO：用户信息 
	 * 
	 */
	
	/**
	 * 方法名：checkUser 
	 * 描述：    根据用户名查询用户信息                 
	 * 参数：    @param name 用户名
	 * 参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/checkUser")
	@ResponseBody
	public JsonResult checkUser(String name) {
		User user = userService.checkUser(name);
		if(user!=null) {
			return new JsonResult("用户存在", 1);
		}
		return new JsonResult("用户不存在", 0);
	}
	
	/**
	 * 方法名：findUserInfo 
	 * 描述：    查询用户信息                  
	 * 参数：    @param session
	 * 参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/userInfos")
	@ResponseBody
	public JsonResult findUserInfo(HttpSession session) { 
		User user = (User) session.getAttribute("user");
		user = userService.getUserByid(user.getId());
		User users = new User();
		users.setName(user.getName());
		users.setNicheng(user.getNicheng());
		users.setAvatar(user.getAvatar());
		users.setTelephone(user.getTelephone());
		users.setQq(user.getQq());
		users.setBalance(user.getBalance());
		users.setFid(user.getFid());
		users.setIcode(user.getIcode());
		users.setAgent_type(user.getAgent_type());
		users.setState(user.getState());
		users.setStatu(user.getStatu());
		return new JsonResult("success",users);
	}
	
	/**
	 * 方法名：changePass 
	 * 描述：   修改用户密码                   
	 * 参数：    @param pass 原密码
	 * 参数：    @param npass 新密码
	 * 参数：    @param request
	 * 参数：    @param session
	 * 参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/changePass")
	@ResponseBody
	public JsonResult changePass(HttpSession session,HttpServletRequest request,String pass, String npass) {
		User user = (User) session.getAttribute("user");
		pass = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(pass.getBytes()).getBytes());
		npass = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(npass.getBytes()).getBytes());
		if(!pass.equals(user.getPass())) {
			return new JsonResult("0", "旧密码输入错误");
		}
		user.setPass(npass);
		userService.updateUserInfo(user);
		User users = userService.login(user.getName(), npass);
		session.setAttribute("user", users);
		new WebSocketJson(8,user.getName(),"你的密码已修改请从新登陆").send();
		SessionListenerUtil.singleLogin(request, user.getName());
		return new JsonResult("1", "修改成功");
	}
	
	/**
	 * 方法名：updateUserInfo 
	 * 描述：    修改用户资料                
	 * 参数：    @param nicheng 用户昵称
	 * 参数：    @param request
	 * 参数：    @return 
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/changeA1")
	public JsonResult updateUserInfo(HttpServletRequest request,String nicheng) {
		User u = (User) request.getSession().getAttribute("user");
		return new JsonResult(String.valueOf(userService.updateUserInfo(u)),userService.getUserByid(u.getId()));
	}

	/**
	 * 方法名：img 
	 * 描述：    批量查询用户的头像                  
	 * 参数：    @param str 用户id
	 * 参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/img")
	@ResponseBody
	public JsonResult img(String str) {
		String[] id = str.split(",");
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < id.length; i++) {
			list.add(new Integer(id[i].trim()));
		}
		List<User> user = liushuiService.img(list);
		return new JsonResult("success", user);
	}
	
	
	/**
	 * 
	 * ----TODO：代理中心管理
	 * 
	 */

	/**
	 * 方法名：userInvitationLink 
	 * 描述：     生成用户的推广链接                  
	 * 参数：    @param session
	 * 参数：    @param request
	 * 参数：    @return 
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/yqm")
	public JsonResult userInvitationLink(HttpSession session, HttpServletRequest request) { 
		User user = (User)session.getAttribute("user");
		if(user.getState() == 2) {
			return new JsonResult("试玩账号无法申请代理，请注册正式账号","试玩账号无法申请代理，请注册正式账号");
		}
		String icode = "";
		String domain = request.getScheme()+"://"+request.getServerName();
		String uid = UUID.randomUUID().toString().replaceAll("-", "").substring(25).toUpperCase() + user.getId();
		if (user.getIcode() != null) {
			String[] code = user.getIcode().split("\\?");
			if(code[0].equals(domain)) {
				icode = user.getIcode();
			}else {
				icode = domain +"?"+ code[1];
				user.setIcode(icode);
			}
		} else {
			icode = domain + "?ref_code=" + uid;
			user.setIcode(icode);
			user.setAgent_type(1);
		}
		userService.updateUserInfo(user);
		user = userService.getUserByid(user.getId());
		User users = new User();
		users.setName(user.getName());
		users.setNicheng(user.getNicheng());
		users.setAvatar(user.getAvatar());
		users.setBalance(user.getBalance());
		users.setIcode(user.getIcode());
		return new JsonResult(icode, user); 
	}
	
	/**
	 * 
	 * ------------用户的充值反水-流水记录
	 * 
	 */

	/**
	 * 查询用户的反水记录 
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/fanshuijl")
	public JsonResult fanshuijl(HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<Liushui> fs = liushuiService.getOneFanshui(user.getId());
		return new JsonResult("fanshuijl", fs);
	}

	/**
	 * 查询用户的流水记录
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/details")
	public JsonResult details(HttpSession session) {
		User user = (User) session.getAttribute("user");
		return new JsonResult(null,liushuiService.getLiushui(user.getId()));
	}

	/**
	 * 查询用户已读的流水记录 
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/duliushui")
	public JsonResult duliushui(String ids) {
		String idss[] = ids.split(",");
		for (int i = 0; i < idss.length; i++) {
			liushuiService.upliushui(Integer.parseInt(idss[i]));
		}
		return new JsonResult("duliushui", null);
	}

	@RequestMapping("/bank")
	public ModelAndView bank(HttpSession session) {
		User user = (User) session.getAttribute("user");
		BankCard bank = bankService.getBankByUid(user.getId());
		return new ModelAndView("u/bank").addObject("bank", bank).addObject("message","pageTest");
	}

	/**
	 * 
	 * -------------用户的每日签到
	 * 
	 */

	/** 每日签到页面 */
	@RequestMapping("/signIn")
	public String signIn() {
		return "/u/meiriqiandao";
	}

	/**
	 * 查询用户是否已签到 
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/signInFlag")
	public JsonResult signInFlag(HttpSession session) {
		User user = (User) session.getAttribute("user");
		String message = "0";
		String signMoney = "0.00";
		if(user.getState() == 2) {
			return new JsonResult("20","试玩账号不能参与签到!");
		}
		Liushui water = liushuiService.checkSigIn(user.getId(),DateUtil.findFormatDate());
		TodayRecord record = yunyingbbService.findOperateRecord("", "", user.getName(),2);
		if (water != null) {
			message = "6";
			signMoney = water.getBdjine()+"";
		}
		User u = userService.getUserByid(user.getId());
		return new JsonResult(message, u.getBalance()+";"+signMoney+";"+record.getMrqiandao());
	}

	/**
	 *  用户进行签到 
	 * @param session
	 * @return
	 */
	@RequestMapping("/signInUser")
	@ResponseBody
	public JsonResult signInUser(HttpSession session) {
		User users = (User) session.getAttribute("user");
		if(users.getState() == 2) {
			return new JsonResult("20","试玩账号不能参与签到!");
		}
		JsonResult jsonResult = liushuiService.signInUserIng(users);
		return jsonResult;
	}

	/**
	 *  查询用户的 签到记录 
	 * @param session
	 * @return
	 */
	@RequestMapping("/record")
	@ResponseBody
	public JsonResult record(HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<Liushui> water = liushuiService.getSignInRecord(user.getId());
		return new JsonResult("record", water);
	}

	/**
	 * 
	 * -----幸运大抽奖
	 * 
	 */

	/*** 幸运大转盘页面 */
	@RequestMapping("	/luckys")
	public String lucky() {
		return "/include/zhuanpan";
	}

	/**
	 * 用户抽奖次数 
	 * @param session
	 * @return
	 */
	@RequestMapping("/luckyCount")
	@ResponseBody
	public JsonResult luckyCount(HttpSession session) {
		User user = (User) session.getAttribute("user");
		if(user.getState() == 2) {
			return new JsonResult("0","试玩账号没有抽奖记录");
		}
		LuckyCount counts = luckyRecordService.getOneLuckyCount(user.getId());
		return new JsonResult("luckyCount", counts.getCount());
	}

	/**
	 * 用户抽奖记录 
	 * @param session
	 * @return
	 */
	@RequestMapping("/luckyRecord")
	@ResponseBody
	public JsonResult luckyRecord(HttpSession session) {
		User user = (User) session.getAttribute("user");
		List<LuckyRecord> records = luckyRecordService.getOneLuckyRecord(user.getId());
		return new JsonResult("luckyRecord", records);
	}

	/**
	 * 随机抽奖记录
	 * @param session
	 * @return
	 */
	@RequestMapping("/mathRecord")
	@ResponseBody
	public JsonResult mathRecord(HttpSession session) {
		List<LuckyRecord> records = luckyRecordService.getMathLuckyRecord();
		return new JsonResult("mathRecord", records);
	}

	/**
	 * 用户抽奖
	 * @param session
	 * @return
	 */
	@RequestMapping("/luckyReckon")
	@ResponseBody
	public JsonResult luckyReckon(HttpSession session) {
		synchronized (this) {
		User users = (User) session.getAttribute("user");
		User user = userService.getUserByid(users.getId());
		if(user.getState() == 2) {
			return new JsonResult("0","试玩账号不能参与抽奖");
		}
		LuckyCount counts = luckyRecordService.getOneLuckyCount(user.getId());
		if (counts.getCount() < 1) {
			return new JsonResult("抽奖次数已用完,请充值后在来", 10);
		} else if (Integer.parseInt(WebsiteStateConfig.configs.get("luckyFlag")) == 0) {
			return new JsonResult("幸运抽奖已暂时关闭,下次开启时间请留意公告!!!", 10);
		}
		List<LuckyLotter> lotter = luckyRecordService.getAllLuckyLotter();
		String[] datas = getPrizeIndex(lotter).split(",");
		int a1 = Integer.parseInt(datas[0]);
		double money = Double.parseDouble(datas[1]);
		int a2 = (int) (Math.random() * 3 + 2);
		String type = "";
		switch (a1) {
		case 1:
			type = lotter.get(0).getLotterType();
			break;
		case 2:
			type = lotter.get(1).getLotterType();
			break;
		case 3:
			type = lotter.get(2).getLotterType();
			break;
		case 4:
			type = lotter.get(3).getLotterType();
			break;
		case 5:
			type = lotter.get(4).getLotterType();
			break;
		case 6:
			type = lotter.get(5).getLotterType();
			break;
		case 7:
			type = lotter.get(6).getLotterType();
			break;
		default:
			type = lotter.get(7).getLotterType();
			break;
		}
		LuckyRecord record = new LuckyRecord();
		record.setName(user.getName());
		record.setType(type);
		record.setMoney(money);
		record.setScope(a2);
		record.setCreateTime(DateUtil.getCurrTime());
		record.setUserid(user.getId());
		luckyRecordService.addLuckyRecord(record);
		counts.setCount(counts.getCount() - 1);
		counts.setCreateTime(DateUtil.getCurrTime());
		luckyRecordService.updateLuckyCount(counts);
		String orderNum = "ZP"+DateUtil.DateFormatOrderNum()+user.getId();
		if (money != 0.00) {
			liushuiService.addActivityRecord(user,orderNum,true,money,"幸运转盘",3);
		}
		return new JsonResult("sucess", type + "," + a2 + "," + money);
		}
	}

	/** 第N个random个就是抽中的奖品 */
	public String getPrizeIndex(List<LuckyLotter> lotter) {
		DecimalFormat dec = new DecimalFormat("#0.00");
		int random = 7;
		double money = 0.00;
		double sumWeight = 0;
		double random1 = 0.00;
		try {
			for (LuckyLotter ls : lotter) {/** 计算总权重 */
				sumWeight += ls.getRebate();
			}
			double randomNumber;
			randomNumber = Math.random();
			double d1 = 0.00;/** 根据随机数在所有奖品分布的区域并确定所抽奖品 */
			double d2 = 0.00;
			for (int i = 0; i < lotter.size(); i++) {
				d2 += (lotter.get(i).getRebate() / sumWeight);
				if (i == 0) {
					d1 = 0;
				} else {
					d1 += (lotter.get(i - 1).getRebate() / sumWeight);
				}
				if (randomNumber > d1 && randomNumber < d2) {
					random = i;
					Double min = Double.parseDouble(lotter.get(i).getLotterMoney().split(",")[0]);
					Double max = Double.parseDouble(lotter.get(i).getLotterMoney().split(",")[1]);
					do {
						random1 = (Math.random() * max);
						random1 = Double.parseDouble(dec.format(random1));
					} while (random1 < min);
					money = random1;
					random += 1;
					return random + "," + money;
				}
			}
		} catch (Exception e) {
			System.out.println("抽奖异常：" + e.getMessage());
		}
		random += 1;
		return random + "," + money;
	}
	
	
	/**
	 * 
	 * --------系统通知
	 * 
	 * 
	 */
	
	/**
	 *   方法名：systemNotice   
	 *   描述：     通知页面                     
	 *   参数：    @param session
	 *   参数：    @return 
	 * @return: ModelAndView
	 */
	@RequestMapping("/systemNotice")
	public ModelAndView systemNotice(HttpSession session) {
		return new ModelAndView("u/systemNotice");
	}

	/**
	 *   方法名：systemNoticeWD   
	 *   描述：     未读流水                     
	 *   参数：    @param paging
	 *   参数：    @param session
	 *   参数：    @return 
	 * @return: String
	 */
	@ResponseBody
	@RequestMapping("/systemNoticeWD")
	public String systemNoticeWD(PagingData paging,HttpSession session) {
		User user = (User) session.getAttribute("user");
		paging.setAllCount(liushuiService.getWDLiushuiCounts(user.getId(),0));
		paging.setList(liushuiService.getWDLiushui(paging.getStartIndex(),paging.getLineCount(),user.getId(),1));
		return PagingData.pagingData(paging);
	}
	
	/**
	 *   方法名：systemNoticeData   
	 *   描述：     已读流水                     
	 *   参数：    @param paging
	 *   参数：    @param session
	 *   参数：    @return 
	 * @return: String
	 */
	@ResponseBody
	@RequestMapping("/systemNoticeYD")
	public String systemNoticeData(PagingData paging,HttpSession session) {
		User user = (User) session.getAttribute("user");
		paging.setAllCount(liushuiService.getWDLiushuiCounts(user.getId(),1));
		paging.setList(liushuiService.getYDLiushui(paging.getStartIndex(),paging.getLineCount(),user.getId(),1));
		return PagingData.pagingData(paging);
	}
	

	/**
	 *   方法名：Querychatrecord   
	 *   描述：     查询聊天室的聊天记录                     
	 *   参数：    @param session
	 *   参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/Querychatrecord")
	@ResponseBody
	public JsonResult Querychatrecord(HttpSession session) {
		User user1 = (User) session.getAttribute("user");
		SimpleDateFormat sdf = new SimpleDateFormat("dd");
		List<Lsltjl> list = liushuiService.query(sdf.format(new Date()));
		return new JsonResult(String.valueOf(user1.getId()), list);
	}
	

	/**
	 *   方法名：panduanshifudenglu   
	 *   描述：      判断用户是否登录                    
	 *   参数：    @param session
	 *   参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping("/panduanshifudenglu")
	@ResponseBody
	public JsonResult panduanshifudenglu(HttpSession session) {
		User user = (User)session.getAttribute("user");
		if(user == null) {
			return new JsonResult(null,0);
		}
		return new JsonResult(user.getAvatar(), 1);
	}
	
	
	/**
	 * 
	 * ----TODO：重复的接口
	 * 
	 */
	

	/**
	 * 查询用户的余额     
	 * @param session
	 * @return
	 */
	@RequestMapping("/userMoney")
	@ResponseBody
	public JsonResult userMoney(HttpSession session) { 
		User user = (User) session.getAttribute("user");
		User u = userService.getUserByid(user.getId());
		session.setAttribute("user", u);
		return new JsonResult(user.getStatu()+"", u.getBalance());
	}
	
	/**
	 * 查询用户的信息		 
	 * @param session
	 * @return
	 */
	@RequestMapping("/userName")
	@ResponseBody
	public JsonResult userName(HttpSession session) { 
		User user = (User) session.getAttribute("user");
		User u = userService.getUserByid(user.getId());
		return new JsonResult(String.valueOf(u.getBalance()),u.getName(),u.getVip(),u.getGamePlayer());
	}
	
	
	
	
	
	
	
	
	/**
	 * 
	 * ----TODO： 更换地址的接口
	 * 
	 */
	
	/**
	 *   方法名：code   
	 *   描述：     生成验证码                
	 *   参数：    @param request
	 *   参数：    @param response
	 *   参数：    @throws Exception 
	 * @return: void
	 */
	@RequestMapping("/code")
	public void code(HttpServletRequest request, HttpServletResponse response) throws Exception {
		CodeUtil.createdCode(request, response);
	}

	/**
	 *  用户注册
	 * @param request 当前请求对象
	 * @param session session对象
	 * @param name 用户名称
	 * @param pass 用户密码
	 * @param invitationCode 邀请码
	 * @param qq 用户QQ
	 * @param code 验证码
	 * @param telephone 电话号码
	 * @return
	 */

	// TODO b
	@RequestMapping("/register")
	@ResponseBody
	public synchronized JsonResult register(HttpServletRequest request, HttpSession session, String name, String pass, 
			String qq, String code, String telephone,String invitationCode) {
		synchronized (this) { // TODO 为什么要用串行化
			try {
				String refCode = (String) session.getAttribute("refCode");//拿到用户当前访问的连接 TODO b 什么意思？
				refCode.split("\\?");//拆分报错就不是用户的推广连接 有可能是总代理的代理连接
			} catch (Exception e) {
				//如果拆分报错  那就是没有用邀请链接
				if(invitationCode == null || "".equals(invitationCode)){
					return new JsonResult("5","请填写邀请码!如果没有邀请码请联系QQ客服");
				}
				if(agencyCenterSevice.pueryagencyInvitationCode(invitationCode) == null){
					return new JsonResult("5","邀请码有误!如果没有邀请码请联系QQ客服");
				}
			}
			if(name.length()>10||name.length()<4) {
				return new JsonResult("5","用户名的长度必须4-10位");
			}
			if(UserNameUtil.isSpecialChar(name)) {
				return new JsonResult("5", "用户名不能包含特殊字符");
			}
			if(UserNameUtil.isContainChinese(name)) {
				return new JsonResult("5", "用户名不能包含中文字符");
			}
				User iuser = userService.checkUser(name);
				if(iuser!=null) {
					return new JsonResult("4", "用户名已存在");
				}
			try {
				String codee = (String) session.getAttribute("code");
				if (!codee.toUpperCase().equals(code.toUpperCase())) {
					return new JsonResult("2", "验证码错误!");
				}
			} catch (Exception e) {
				new JsonResult("0","请刷新验证码!");
			}
			
			//注册ip地址 
			String ip = IpAddrUtil.getIpAddr(request);
			if (!systemConfigService.ipCheck(ip,1)) {
				return new JsonResult("3", "注册次数过多，请明日注册!"); 
			}
			
			//用户注册
			int num = userService.register(session,request,name, pass, invitationCode, qq, ip, telephone);
			String md5 = DigestUtils.md5DigestAsHex(pass.getBytes());
			String pwd = DigestUtils.md5DigestAsHex(md5.getBytes());
			User user = userService.login(name, pwd);
			session.setAttribute("user", user);

			WebSocketJson w = new WebSocketJson(4,user.getName());
			w.sendAllHt();
			Set<User> set = SessionListenerUtil.onlineNum(request);
			if(set.size() > 0) {
				WebSocketJson w1 = new WebSocketJson(2,set.size());
				w1.sendHt();
			}
			return new JsonResult(String.valueOf(num), "恭喜你,注册成功");
		}
	}
	
	/** 
	 * 用户登录
	 * @param request 当前请求对象
	 * @param session 当前session对象
	 * @param name 用户帐号
	 * @param pass 用户密码
	 * @param code 验证码
	 * @return
	 */

	@RequestMapping("/login")
	@ResponseBody
	public JsonResult login(HttpServletRequest request, HttpSession session, String name, String pass, String code) {
		String ip1 = IpAddrUtil.getIpAddr(request);
		if(session.getAttribute("user")!=null) {
			return new JsonResult("4", "登录成功");
		}
		userService.addTourists(ip1, "登录");
		try {
			String scode = (String) session.getAttribute("code");
			if (!scode.toUpperCase().equals(code.toUpperCase())) {
				//1 验证码输入错误 请从新输入
				return new JsonResult("1", "验证码输入错误!");
			}
		} catch (Exception e) {
			//0 请刷新验证码
			return new JsonResult("0","请刷新验证码");
		}
		User user = userService.login(name, DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(pass.getBytes()).getBytes()));
		if(user!=null) {
			if (user.getState() == 0) {
				//2 账号已被管理员禁用，请联系客服
				return new JsonResult("2", "账号已被禁用，请联系管理员");
			} else if (user.getState() == 1) {
				// 最后登录ip
				String ip = IpAddrUtil.getIpAddr(request);
				WhiteList whiteList = systemConfigService.findWhiteListByIP(ip);
				if (whiteList != null && whiteList.getStatus() == 0) {
					//改ip已经被禁用，请更换ip重新登录
					return new JsonResult("3", "该ip被禁用，请更换ip重新登录");
				}
				// 未登录时间
				String retime = user.getLastTime();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				long t1 = 0;
				String t3 ="";
				try {
					t1 = sdf.parse(retime).getTime();
					t3 = "未登录"+(int) (((new Date().getTime() - t1) / 1000) / 86400) + "天";
				} catch (ParseException e) {
				}
				user.setLastTime(DateUtil.getCurrTime());
				user.setNotTime(t3); 
				user.setLastIp(ip);
				userService.updateUserInfo(user);
				new WebSocketJson(7,name,"你的账号在另外一个地方登陆，如果不是你本人操作请及时修改密码").send();
				SessionListenerUtil.singleLogin(request, name);
				session.setAttribute("user", user);
				WebSocketJson w = new WebSocketJson(3,user.getName());
				w.sendAllHt();
				Set<User> set = SessionListenerUtil.onlineNum(request);
				if(set.size() > 0) {
					WebSocketJson w1 = new WebSocketJson(2,set.size());
					w1.sendAllHt();
				}
				return new JsonResult("4", "登录成功");
			} else {
				SessionListenerUtil.singleLogin(request, name);
				session.setAttribute("user", user);
				WebSocketJson w = new WebSocketJson(3,user.getName());
				w.sendAllHt();
				Set<User> set = SessionListenerUtil.onlineNum(request);
				if(set.size() > 0) {
					WebSocketJson w1 = new WebSocketJson(2,set.size());
					w1.sendAllHt();
				}
				return new JsonResult("4", "登录成功");
			}
		}else {
			return new JsonResult("5", "账号或者密码错误");//5账号密码错误 
		}
	}
	
	/**
	 * 方法名：tryPlayAcount 
	 * 描述：     生成试玩账号                  
	 * 参数：    @return 
	 * @return: JsonResult
	 */
	@ResponseBody
	@RequestMapping("/tryPlayAcount")
	public JsonResult tryPlayAcount() {
		String str = "guest";
		Random random = new Random();
		while (true) {
			String acount = str + random.nextInt();
			User user = userService.checkUser(acount);
			if(user==null) {
				return new JsonResult("success",acount);
			}
		}
	}
	
	/**
	 * 方法名：tryplay 
	 * 描述：    试玩帐号注册                  
	 * 参数：    @param users
	 * 参数：    @param name 用户名	
	 * 参数：    @param pass 用户密码	
	 * 参数：    @param session
	 * 参数：    @param request
	 * 参数：    @return 
	 * @return: JsonResult
	 */
	@RequestMapping(value = "/tryplay")
	@ResponseBody
	public JsonResult tryplay(User user,HttpSession session,HttpServletRequest request) {
		User users = (User)session.getAttribute("user");
		if(users != null) {
			return new JsonResult("10","你已经登录不可在试玩！");
		}
		if(UserNameUtil.isSpecialChar(user.getName())) {
			return new JsonResult("5", "用户名不能包含特殊字符!");
		}
		if(user.getName().length()>25||user.getName().length()<4) {
			return new JsonResult("5","用户名的长度必须4-10位!");
		}
		if(UserNameUtil.isContainChinese(user.getName())) {
			return new JsonResult("5", "用户名不能包含中文字符!");
		}
		String ipAddress = IpAddrUtil.getIpAddr(request);
		if (!systemConfigService.ipCheck(ipAddress,2)) {
			return new JsonResult("2", "试玩次数过多，请明日注册！");
		}
		synchronized (this) {
			userService.addTourists(ipAddress, "试玩账号");
			User iuser = userService.checkUser(user.getName());
			String pass = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(user.getPass().getBytes()).getBytes());
			if(iuser!=null) {
				if(!pass.equals(iuser.getPass())) {
					return new JsonResult("3", "密码错误,请重新登录或注册试玩账号！");
				}else {
					session.setAttribute("user", iuser);
					return new JsonResult("1", "success");
				}
			}
			user.setPass(pass);
			user.setRegisterIp(ipAddress);
			user.setLastIp(ipAddress);
			userService.userTryplay(user);
			User userInfo = userService.login(user.getName(), pass);
			session.setAttribute("user", userInfo);
			return new JsonResult("1", "success");
		}
	}
	
}
